<template>
  <view class="container">
    <view class="form">
      <view class="form-item">
        <text class="label">旧密码:</text>
        <input v-model="oldPassword" class="input" type="password" placeholder="请输入旧密码"/>
      </view>
      <view class="form-item">
        <text class="label">新密码:</text>
        <input v-model="newPassword" class="input" type="password" placeholder="请输入新密码"/>
      </view>
      <view class="form-item">
        <text class="label">确认新密码:</text>
        <input v-model="confirmNewPassword" class="input" type="password" placeholder="请确认新密码"/>
      </view>
      <button class="save-btn" :disabled="!isFormValid" @click="changePassword">保存</button>
    </view>
  </view>
</template>

<script setup>
import {computed, ref} from 'vue'
import {changePasswordAPI, checkOldPasswordAPI} from '../../api/userMG' // 导入旧密码检查和密码修改接口

const oldPassword = ref('')
const newPassword = ref('')
const confirmNewPassword = ref('')
// 计算属性用于检查表单是否有效
const isFormValid = computed(() => {
  return oldPassword.value !== '' && newPassword.value !== '' && confirmNewPassword.value !== '' && newPassword.value === confirmNewPassword.value
})
const changePassword = async () => {
  if (newPassword.value !== confirmNewPassword.value) {
    uni.showToast({
      title: '新密码与确认密码不一致',
      icon: 'error'
    })
    return
  }

  try {
    const checkOldPasswordResponse = await checkOldPasswordAPI({password: oldPassword.value})
    if (checkOldPasswordResponse !== true) {
      uni.showToast({
        title: '旧密码不正确',
        icon: 'error'
      })
      return
    }

    const changePasswordResponse = await changePasswordAPI({passwordWbxqy: newPassword.value})
    if (changePasswordResponse === undefined) {
      uni.showToast({
        title: '密码修改成功',
        icon: 'success'
      })
      // 密码修改成功后，可以跳转到登录页面或者其他页面
    } else {
      uni.showToast({
        title: '密码修改失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('修改密码失败', error)
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background-color: #f5f5f5;
}

.form {
  width: 100%;
  max-width: 400px;
  display: flex;
  flex-direction: column;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.label {
  width: 80px;
}

.input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.save-btn {
  margin-top: 20px;
  padding: 10px;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  text-align: center;
}
</style>
